<?php

namespace app\admin\controller\merchant;
/**
 *  @icon fa fa-ads
 **/
class User extends Base
{

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = loader('admin')->loadModel('tyyh\\User');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $search = $this->request->param('search');
            if($search) {
                $where = [
                    'id|nickname|username|phone' => ['like', "%" . $search . '%']
                ];
            }
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post('row/a');
            $validate = $this->loader->loadAny('validate', 'tyyh\\User');
            if(!$validate->scene('edit')->check($post)) {
                $this->error($validate->getError());
            }
            $this->model->save($post, ['id' => $ids]);
            $this->success();
        }
        $row = $this->model->where(['id' => $ids])->find();
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     *  查看用户信息
     */
    public function info($ids = null) {
        $row = $this->model->where(['id' => $ids])->find();
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function edit_pass($id = null) {
        if ($this->request->isPost()) {
            $post = $this->request->post('row/a');

            $validate = $this->loader->loadAny('validate', 'tyyh\\User');
            if(!$validate->scene('set_password')->check($post)) {
                $this->error($validate->getError());
            }
            $passwordTool = loadTool('Password');
            $result = $passwordTool->encryption($post['password'], '', true);
            $row = $this->loader->loadModel('tyyh\\User')->find($post['id']);
            $row->password = $result['password'];
            $row->salt = $result['salt'];
            $row->save();
            $this->success();
        }
        $row = $this->model->where(['id' => $id])->find();
        $this->assign('row', $row);
        return $this->view->fetch();
    }

}
